package cn.tedu.service.impl;

import cn.tedu.dao.GoodsDao;
import cn.tedu.dao.SaleDao;
import cn.tedu.domain.Goods;
import cn.tedu.domain.Sale;
import cn.tedu.excep.NotEnoughException;
import cn.tedu.service.BuyGoodsService;

public class BuyGoodsServiceImpl implements BuyGoodsService {
    private GoodsDao goodsDao;
    private SaleDao saleDao;

    @Override
    public void buy(Integer goodsID, Integer nums) {
        System.out.println("===buy方法的开始===");
        //记录销售信息，向sale表中添加记录
        Sale Newsale = new Sale();
        Newsale.setGid(goodsID);
        Newsale.setNums(nums);
        saleDao.insertSale(Newsale);

        //更新goods表中的库存信息
        Goods goods = goodsDao.selectGoods(goodsID);
        if (goods==null){
            //购买商品不存在
            throw new NullPointerException("编号为："+goodsID+"的商品不存在");
        }else if (goods.getAmount()<nums){
            //购买商品库存不足
            throw new NotEnoughException("编号为："+goodsID+"的商品库存不足啦");
        }else {
            //把传入的参数赋值给一个对象，在传入更新goods表库存的方法
            Goods buyGoods = new Goods();
            buyGoods.setId(goodsID);
            buyGoods.setAmount(nums);
            goodsDao.updateGoods(buyGoods);
            System.out.println("===buy方法的结束===");
        }


    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }


}
